package com.tiny.work.test.stackoverflow;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class C1 {
    public static void main(String[] args) throws Exception {
        int bufSize = 4096; // 4k buffer.
        byte[] buffer = new byte[bufSize];
        int bytesAvailable, bytesRead;
        File outfile = new File("/Users/zhaolulun/MyProduce/c.txt");

        FileOutputStream myOutputStream  = new FileOutputStream(outfile);


        try {
            while ( true ) {
                bytesAvailable = System.in.available(); // seems may throw IOException if InputStream is closed.
//                bytesAvailable  = System.in.read(buffer, 0, bytesAvailable);
                if ( bytesAvailable > 0 ) {
                    if ( bytesAvailable > bufSize ) {
                        bytesAvailable = bufSize;
                    }

                    System.out.println();

                    System.out.println(System.in.available());
                    System.out.println(bytesAvailable);

                    // The following statement seems should not block.
                    bytesRead = System.in.read(buffer, 0, bytesAvailable);
//                    printArray(buffer);
                    if ( bytesRead == -1 ) {
                        myOutputStream.close();
                        System.out.println("NonBlockingReadTest : return by EOF.");
                        return;
                    }
                    myOutputStream.write(buffer, 0, bytesRead);
                    myOutputStream.flush();
                } else if ( bytesAvailable == 0 ) {
                    // Nothing to do, just loop over.
                } else {
                    // Error ! Should not be here !
                }
            }
        } catch (IOException e) {
        }
    }
    public static void printArray(byte[] result ){
        if (result == null || result.length == 0) return;
        for (byte data: result) {
            System.out.print(data);
        }
        System.out.println();
    }
}